package com.hlg.xboot.aop;

import com.hlg.xboot.exceptions.ParameterException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

/**
 * <p>控制器参数验证aop</p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company: 中视数讯</p>
 * <p>Site: www.digi-zones.com</p>
 *
 * @author yangxin
 * @version 1.0
 * @date 2016/8/6
 */
@Component
@Aspect
public class ControllerValidationAspectJ {

    @Pointcut("execution(* com.hlg.xboot.web.controller..*.*(..))")
    public void cutController(){
        
    }
    
    @Around("cutController()")
    public Object validate(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        for (Object arg : args) {
            if (arg instanceof BindingResult) {
                BindingResult result = (BindingResult) arg;
                if (result.hasErrors()) {
                    FieldError fieldError = result.getFieldErrors().get(0);
                    throw new ParameterException(fieldError.getDefaultMessage());
                }
                break;
            }
        }
        return point.proceed();
    }

}